package org.atlantis.grosbeak.lang;

/**
 * 用于计时的毫秒表。
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">SeeNoEvil</a>
 */
public class Stopwatch {

	private long begin;
	private long end;

	public static Stopwatch begin() {
		Stopwatch sw = new Stopwatch();
		sw.start();
		return sw;
	}

	public static Stopwatch create() {
		return new Stopwatch();
	}

	public static Stopwatch run(Runnable r) {
		Stopwatch sw = begin();
		r.run();
		sw.stop();
		return sw;
	}

	public long start() {
		begin = System.currentTimeMillis();
		return begin;
	}

	public long stop() {
		end = System.currentTimeMillis();
		return end;
	}

	public long getDuration() {
		return end - begin;
	}

	public long getStartTime() {
		return begin;
	}

	public long getEndTime() {
		return end;
	}

	@Override
	public String toString() {
		return String.format("Total: %dms : [%s] => [%s]", this.getDuration(),
				new java.sql.Timestamp(begin).toString(),
				new java.sql.Timestamp(end).toString());
	}
}
